package com.jt.yygh.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jt.yygh.hospital.entity.hosp.Department;
import com.jt.yygh.hospital.repository.DepartmentRepository;
import com.jt.yygh.hospital.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.*;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author jiang tao
 * @date 2022/3/1
 * @description:
 **/
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap),Department.class);
        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());
        if(targetDepartment != null){
            BeanUtils.copyProperties(department, targetDepartment, Department.class);
        }else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
        }
        departmentRepository.save(targetDepartment);

    }


    @Override
    public Page<Department> getDepartmentsByHoscodeAndDepcode(Map<String, Object> departmentQuery) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0 为第一页
        Pageable pageable = PageRequest.of((int) departmentQuery.get("page")-1, (int) departmentQuery.get("limit"), sort);

        Department department = new Department();
        department.setIsDeleted(0);
        department.setDepcode((String) departmentQuery.get("depcode"));
        department.setHoscode((String) departmentQuery.get("hoscode"));

        //创建匹配器
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //创建实例
        Example<Department> example = Example.of(department, matcher);
        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);
        if(department != null){
            departmentRepository.deleteById(department.getId());
        }


    }
}
